/**
 * 调用网易云接口获取音乐
 */

const axios = require('axios')
const md5 = require('md5-node')
const utils = require('../common/utils')

axios.defaults.withCredentials = true

const host = 'https://autumnfish.cn'

let login = {
  url: host + '/login/cellphone',
  method: 'post',
  data: {
    phone: 13005349055,
    md5_password: md5('szt20020901')
  }
}

let likeId = {
  url: host + '/likelist',
  method: 'get',
  headers: {
    cookie: ''
  },
  params: {
    uid: ''
  }
}

let allId = []

let musicDetail = {
  url: host + '/song/detail',
  method: 'get',
  params: {
    ids: ''
  }
}

let musicUrl = {
  url: host + '/song/url',
  method: 'get',
  params: {
    id: ''
  }
}

let datas = {
  code: 200,
  result: []
}


function getMusic(num) {
  return new Promise((resolve, reject) => {
    if (likeId.params.uid === '' && likeId.headers.cookie === '') {
      axios(login).then(suc => {
        likeId.params.uid = suc.data.profile.userId
        likeId.headers.cookie = suc.data.cookie
        resolve()
      }).catch(err => {
        reject(err)
      })
    } else {
      resolve()
    }
  }).then(suc => {
    return new Promise((resolve, reject) => {
      if (musicDetail.params.ids === '' && musicUrl.params.id === '') {
        axios(likeId, { withCredentials: true }).then(likeInfo => {
          allId = likeInfo.data.ids
          resolve()
        }).catch(err => {
          reject(err)
        })
      } else {
        resolve()
      }
    })
  }).then(suc => {
    return new Promise((resolve, reject) => {
      let ids = random(allId, num).join(',')
      musicDetail.params.ids = ids
      musicUrl.params.id = ids

      axios.all([
        axios(musicDetail),
        axios(musicUrl)
      ]).then(axios.spread((res1, res2) => {
        let details = []
        let urls = []
        details = res1.data.songs
        urls = res2.data.data

        if (details.length !== undefined && urls.length !== undefined) {
          for (let i = 0; i < details.length; i++) {
            for (let j = 0; j < urls.length; j++) {
              if (details[i].id === urls[j].id) {
                details[i].url = urls[j].url
                break
              }
            }
          }
        }

        datas.result = details

        resolve(datas)
      })).catch(err => {
        reject(err)
      })
    })
  })

}

function random(arr, num = 10) {
  let newArr = []

  for (let i = 0; i < num; i++) {
    let ranNum = utils.randomNum(0, arr.length - 1)
    newArr.push(arr[ranNum])
    arr.splice(ranNum, 1)
  }

  return newArr
}


module.exports = {
  getMusic
}


